package com.mall.service

import com.mall.entity.Admin
import com.mall.mapper.AdminMapper
import com.mall.util.JwtUtil
import com.mall.util.PasswordUtil
import org.springframework.stereotype.Service

/**
 * 管理员服务类
 */
@Service
class AdminService(
    private val adminMapper: AdminMapper,
    private val jwtUtil: JwtUtil,
    private val passwordUtil: PasswordUtil
) {

    /**
     * 注册管理员
     */
    fun register(admin: Admin) {
        // 对密码进行加密处理
        val hashedPassword = passwordUtil.hashPassword(admin.password)
        admin.password = hashedPassword
        adminMapper.insert(admin)
    }

    /**
     * 管理员登录
     */
    fun login(username: String, password: String): Map<String, Any> {
        // 根据用户名查找管理员
        val admin = adminMapper.findByUsername(username)
            ?: throw Exception("用户名不存在")

        // 验证密码是否正确
        if (!passwordUtil.checkPassword(password, admin.password)) {
            throw Exception("密码错误")
        }

        // 生成JWT token
        val token = jwtUtil.generateToken(admin)

        return mapOf(
            "admin" to admin,
            "token" to token
        )
    }

    /**
     * 更新管理员信息
     */
    fun update(admin: Admin) {
        if (!admin.password.isNullOrEmpty()) {
            val hashedPassword = passwordUtil.hashPassword(admin.password)
            admin.password = hashedPassword
        }
        adminMapper.update(admin)
    }

    /**
     * 删除管理员
     */
    fun delete(id: Long) {
        adminMapper.delete(id)
    }

    /**
     * 获取管理员列表
     */
    fun list(page: Int, pageSize: Int): Map<String, Any> {
        val offset = (page - 1) * pageSize
        val admins = adminMapper.findAll(offset, pageSize)
        val total = adminMapper.count()

        return mapOf(
            "data" to admins,
            "total" to total
        )
    }
}